// 导入依赖的模块
yepjs.require("jquery");
yepjs.require("YBA.Common");
yepjs.require("YBA.Plugin.plugins");
yepjs.require("YBA.Logic.User.list");


// 部门管理 - 部门列表
yepjs.define("list", {

    NS: "YBA.Logic.Department",

    field: function() {

        var Biz = {
            // 初始化事件
            init: function() {
                Biz.fn.getData(function(){
                    for (var i in Biz.event) {
                        Biz.event[i]();
                    }
                });
            },
            //  公共变量
            vars: {
                // 模板列表
                tpl: (function(){
                    var tpl = {};
                    $("script[type='text/ysmart']").each(function(){
                        var t = $(this);
                        tpl[t.attr("data-name")] = t.html();
                    });
                    return tpl;
                })(),
                // 当前选中的部门机构id
                selectedVal: null,
                // 用户列表模块的引用
                userLogic: YBA.Logic.User.list()
            },
            // 页面元素
            el: {
                body: $("body"),
                jtreeHover: $("#j-treeHover"),
                jdepartTree: $("#j-departTree"),
                jtreeDelete:$("#j-treeDelete")
            },
            // 功能函数集合
            fn: {
                // 读取机构列表数据
                getData: function(callback){
                    YBA.Data.Department.getDeptList({
                    	startPos: 1,
                        pageSize: 0,
                        parentId: 0
                    }, function(json){
                        if(json.code == 200){
                            Biz.fn.createList(json.objList);
                            callback && callback();
                        }else{
                            YBA.Plugin.msgtip({type: "i", msg: "读取机构数据失败"});
                        }
                    });
                },
                // 生成列表
                createList: function(data){
                    var html = [], uper = -1;
                    var createList = function(dataItem){
                        uper++;
                        var tmpHtml = [];
                        tmpHtml.push('<ul>');
                        for(var i=0,len=dataItem.length;i<len;i++){
                            tmpHtml.push('    <li>');
                            if(i == 0 && uper == 0){
                            	tmpHtml.push('        <div data-order="' + dataItem[i].iorder + '" data-value="' + dataItem[i].id + '" data-text="' + dataItem[i].name + '" style="padding-left:' + uper*20 + 'px" class="ui-treeSelectItem j-item parent'+ (dataItem[i].id == Biz.vars.selectedVal ? "select": "") +'">');
                            }else{
                            	tmpHtml.push('        <div data-order="' + dataItem[i].iorder + '" data-value="' + dataItem[i].id + '" data-text="' + dataItem[i].name + '" style="padding-left:' + uper*20 + 'px" class="ui-treeSelectItem j-item '+ (dataItem[i].id == Biz.vars.selectedVal ? "select": "") +'">');
                            }                      
                            if(dataItem[i].hasChildren){
                                tmpHtml.push('            <span class="tree-ico"><i class="ui-tree-ico ui-ico-open"></i></span>');
                            }
                            tmpHtml.push('            <span>' + dataItem[i].name + '</span>');
                            tmpHtml.push('        </div>');
                            if(dataItem[i].hasChildren){
                                tmpHtml.push(createList(dataItem[i].children));
                            }
                            tmpHtml.push('    </li>');
                        }
                        tmpHtml.push('</ul>');
                        uper--;
                        return tmpHtml.join("");
                    };
                    html.push(createList(data));
                    Biz.el.jdepartTree.html(html.join(""));
                },
                // 设置选中的部门
                setSelectedId: function(id){
                    Biz.vars.selectedVal = id;
                    Biz.vars.userLogic.api.setDepartId(id);
                },
                // 删除指定机构
                delDepart: function(id, text){
                    var confirm = YBA.Plugin.confirm({
                        msg: "您确定要删除&quot;" + text + "&quot;吗？",
                        yes: function(){
                            confirm.hide();
                            YBA.Data.Department.deleteDept({id: id}, function(json){
                                if(json.code == 200){
                                    YBA.Plugin.msgtip({type: "o", msg: json.desc});
                                    Biz.fn.getData();
                                }else{
                                    YBA.Plugin.msgtip({type: "i", msg: json.desc});
                                }
                            });
                        }
                    });
                },
                // 修改指定机构
                editDepart: function(data){
                    var popform = new YBA.Plugin.popform({
                        title: "编辑",
                        content: YBA.Common.ysmart(Biz.vars.tpl.editDepartTpl, data),
                        destroy: true,
                        width: 500,
                        onHide: function () {
                            // 隐藏弹窗时要执行的回调函数
                        },
                        onShow: function () {
                            // 显示弹窗时要执行的回调函数
                        },
                        btns: [{
                            value: "保存",
                            className: "btn blue g-mr10",
                            fn: function () {
                                var data = popform.self.find("form").serialize();
                                YBA.Data.Department.updateDept(data, function(json){
                                    if(json.code == 200){
                                        YBA.Plugin.msgtip({type: "o", msg: json.desc});
                                        Biz.fn.getData();
                                        popform.hide();
                                    }else{
                                        YBA.Plugin.msgtip({type: "i", msg: json.desc});
                                    }
                                });
                            }
                        }, {
                            value: "取消",
                            className: "btn red g-ml10",
                            fn: function () {
                                popform.hide();
                            }
                        }]
                    }).show();
                },
                // 新增机构
                addDepart: function(data){
                    var popform = new YBA.Plugin.popform({
                        title: "增加部门",
                        content: YBA.Common.ysmart(Biz.vars.tpl.addDepartTpl, data),
                        destroy: true,
                        width: 500,
                        onHide: function () {
                            // 隐藏弹窗时要执行的回调函数
                        },
                        onShow: function () {
                            // 显示弹窗时要执行的回调函数
                        },
                        btns: [{
                            value: "保存",
                            className: "btn blue g-mr10",
                            fn: function () {
                                var data = popform.self.find("form").serialize();
                                console.log(data)
                                YBA.Data.Department.addDept(data, function(json){
                                    if(json.code == 200){
                                        YBA.Plugin.msgtip({type: "o", msg: json.desc});
                                        Biz.fn.getData();
                                        popform.hide();
                                    }else{
                                        YBA.Plugin.msgtip({type: "i", msg: json.desc});
                                    }
                                });
                            }
                        }, {
                            value: "取消",
                            className: "btn red g-ml10",
                            fn: function () {
                                popform.hide();
                            }
                        }]
                    }).show();
                }
            },
            // 初始化时执行的所有事件
            event: {
                // 选择列表项
                chooseItem: function(){
                    Biz.el.jdepartTree.delegate(".j-item", "click", function(e){
                        var t = $(this), li = t.closest("li"), id = t.attr("data-value"), txt = li.attr("data-text");
                        Biz.fn.setSelectedId(id);
                        Biz.el.jdepartTree.find(".j-item").removeClass("select");
                        t.addClass("select");
                    });
                },
                // 分支展开折叠
                toggleTree: function(){
                    Biz.el.jdepartTree.delegate(".ui-tree-ico", "click", function(e){
                        var t = $(this), children = t.closest("li").find(">ul");
                        if(t.hasClass("ui-ico-open")){
                            t.removeClass("ui-ico-open").addClass('ui-ico-close');
                            children.hide();
                        }else{
                            t.removeClass("ui-ico-close").addClass('ui-ico-open');
                            children.show();
                        }
                        e.stopPropagation();
                    });
                },
                // 显示列表项菜单
                itemMenu: function(){

                    var timer = null, curItem;

                    // 鼠标移动到机构列表上，显示功能菜单
                    Biz.el.jdepartTree.delegate(".j-item", "mouseover", function(e){
                        clearTimeout(timer);
                        var t = $(this), offset = t.offset(), left = offset.left, top = offset.top, width = t.innerWidth(), height = t.height();
                        curItem = t;
                        if(t.hasClass("parent")){
                        	Biz.el.jtreeDelete.hide();
                        }else{
                        	Biz.el.jtreeDelete.show();
                        }
                        Biz.el.jtreeHover.css({left: left + width, top: top}).show();
                        Biz.el.jdepartTree.find(".j-item").removeClass("hover");
                        t.addClass("hover");
                    });

                    // 鼠标离开机构列表，隐藏功能菜单
                    Biz.el.jdepartTree.delegate(".j-item", "mouseout", function(e){
                        var t = $(this);
                        timer = setTimeout(function(){
                            t.removeClass("hover");
                            Biz.el.jtreeHover.hide();
                        },100);
                    });

                    // 鼠标移动到功能菜单上
                    Biz.el.jtreeHover.hover(function(){
                        clearTimeout(timer);
                    }, function(){
                        timer = setTimeout(function(){
                            Biz.el.jtreeHover.hide();
                            curItem.removeClass("hover");
                        },100);
                    });

                    // 点击功能菜单
                    Biz.el.jtreeHover.delegate(".j-menuitem", "click", function(){
                        var t = $(this), id = curItem.attr("data-value"), text = curItem.attr("data-text"), order = curItem.attr("data-order");
                        Biz.el.jtreeHover.trigger("mouseout");

                        switch(t.attr("data-type")){
                            case "del":
                                Biz.fn.delDepart(id, text);
                                break;
                            case "edit":
                                Biz.fn.editDepart({id: id, text: text, order: order});
                                break;
                            case "viewUser":
                                curItem.click();
                                break;
                            case "addDepart":
                                Biz.fn.addDepart({parentId: id, parentText: text});
                                break;
                        }
                    });
                }
            }
        };

        Biz.init();

        return Biz;
    }
});
